package com.comp3111.happymeal;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.configuration.Configuration;
import com.configuration.Owner;
import com.controller.RestaurantCommentUpdate;
import com.controller.MealFetch;
import com.controller.RestaurantCommentFetch;
import com.controller.RestaurantFetch;
import com.controller.UserFetch;
import com.object.Meal;
import com.object.Restaurant;
import com.object.RestaurantComment;
import com.object.User;
import com.user.Helper;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.SimpleAdapter.ViewBinder;

public class RestaurantPageActivity extends NavigationDrawerActivity {
	
	//Interface element
	private ListView mealListView;
	private SimpleAdapter mealAdapter;
	private ListView restaurantCommentListView;
    private SimpleAdapter restaurantCommentAdapter;
    private RatingBar ratingBar;
    //private TextView ratingValue;
    
    //Allow display only 5 meals of from the restaurant in the restaurant page
    final int NUM_MEAL = 5;
    
    //Class attribute for loading pictures
    //Drawable restaurantPicture;
    
    Drawable tmpPicture;
    String mealPictureDrawableURL;
    
    //Drawable tmpPicture;
    String userProfilePictureDrawableURL;
    
    //Class shared variable
    int restaurantId;
    
    //List for containing the id of the food
    private List<Integer> mealIdList;	//Id for the food list for that restaurant
    private List<Integer> userIdList;	//Id for the comment list for that restaurant
    private List<Integer> commentIdList;	//Id of the restaurant comment
    
    //Selected meal comment id
    int selectedComment;
    
    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        setContentView(R.layout.restaurant_page);//for user review layout, please see user_review.xml
        createDrawer();
        
        addListenerOnRatingBar();
        
        //Get Data from intent
        restaurantId = Integer.parseInt(extras.getString("RESTAURANTID"));	//Check out discoverPageActivity onClickListener
        
        //Fetch the meal of id
      	RestaurantFetch restaurantFetch = new RestaurantFetch();
      	Restaurant restaurant = restaurantFetch.fetchRestaurantById(restaurantId);
      	RestaurantCommentFetch restaurantCommentFetch = new RestaurantCommentFetch();
      	
      	//Fetch number of meal
      	MealFetch mealFetch = new MealFetch();
      		
      	//Get the variable of textview
      	TextView tv_restaurant_page_name = (TextView)findViewById(R.id.restaurant_page_name);
      	TextView tv_restaurant_page_rating = (TextView)findViewById(R.id.restaurant_page_rating);
      	TextView tv_restaurant_page_open_hours = (TextView)findViewById(R.id.restaurant_page_open_hours);
      	TextView tv_restaurant_page_description = (TextView)findViewById(R.id.restaurant_page_description);
      	TextView tv_restaurant_page_number_of_food = (TextView)findViewById(R.id.rest_food);
      	TextView tv_restaurant_page_telephone = (TextView)findViewById(R.id.restaurant_page_telephone);
      		
      	
      	//Set Text for the textview
      	tv_restaurant_page_name.setText(restaurant.getName());
      	tv_restaurant_page_rating.setText("Rating: " + Float.toString(restaurantCommentFetch.fetchRestaurantRating(restaurantId)) + "/5");
      	tv_restaurant_page_open_hours.setText(restaurant.getOpenHours());
      	//Get the variable of imageview
      	View iv_restaurant_page_picture = (View)findViewById(R.id.restaurant_page_picture);
      	iv_restaurant_page_picture.setTag(Configuration.baseURL + restaurant.getProfilePicture());
      	new DownloadImagesTask().execute(iv_restaurant_page_picture);
      	tv_restaurant_page_description.setText(restaurant.getDescription());
      	tv_restaurant_page_number_of_food.setText("Food" + " (" + Integer.toString(mealFetch.fetchMealCountByRestaurantId(restaurantId)) + ")");
      	tv_restaurant_page_telephone.setText(restaurant.getTelephone());
      		
        mealListView = (ListView)findViewById(R.id.restaurant_page_food_listview);
        mealAdapter = new SimpleAdapter(this,getMealListView(),R.layout.restaurant_page_food_list,
        		new String[]{"food_pic","food_name", "price"},
    			new int[]{R.id.restaurant_page_food_list_picture, R.id.restaurant_page_food_list_name, R.id.restaurant_page_food_list_price});
        
        mealListView.setAdapter(mealAdapter);
        mealAdapter.setViewBinder(new ViewBinder(){
        	public boolean setViewValue(View view,Object data,String textRepresentation){
				if(view instanceof ImageView && data instanceof Drawable){
					ImageView iv=(ImageView)view;
					iv.setImageDrawable((Drawable)data);
					return true;
				}
				else return false;
			}
        });
        
        mealListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            	int mealId = mealIdList.get(position);
                //Toast.makeText(DiscoverPageActivity.this,"ID���G" + Integer.toString(mealId) ,Toast.LENGTH_SHORT).show();
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(RestaurantPageActivity.this, FoodPageActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("MEALID",Integer.toString(mealId).trim());
					
				//Go to next page
				startActivity(intentPass);
            }
        });  
        
        Helper.setListViewHeightBasedOnChildren(mealListView);
              
        //getRestaurantComment
        restaurantCommentListView = (ListView)findViewById(R.id.listView);
        restaurantCommentAdapter = new SimpleAdapter(this, getRestaurantComment(), R.layout.restaurant_user_review,
        		new String[]{"user_review_pic", "user_name","comments","time", "user_rating"},
				new int[]{R.id.restaurant_user_review_pic, R.id.restaurant_review_user_name, R.id.restaurant_review_comments, R.id.restaurant_review_time, R.id.restaurant_review_rating});
        restaurantCommentListView.setAdapter(restaurantCommentAdapter);
        restaurantCommentAdapter.setViewBinder(new ViewBinder(){
        	public boolean setViewValue(View view,Object data,String textRepresentation){
				if(view instanceof ImageView && data instanceof Drawable){
					ImageView iv=(ImageView)view;
					iv.setImageDrawable((Drawable)data);
					return true;
				}
				else return false;
			}
        });
        
        restaurantCommentListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
            	int userId = userIdList.get(position);
                //Toast.makeText(DiscoverPageActivity.this,"ID���G" + Integer.toString(mealId) ,Toast.LENGTH_SHORT).show();
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(RestaurantPageActivity.this, UserProfileActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("USERID",Integer.toString(userId).trim());
					
				//Go to next page
				startActivity(intentPass);
            }
        });
        
        /*
         * Alert dialog for deletion of comment
         */
        AlertDialog.Builder builder1 = new AlertDialog.Builder(RestaurantPageActivity.this);
        builder1.setMessage("Do you want to remove your comment?");
        builder1.setCancelable(true);
        builder1.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	/*
            	 * TODO : Remove that comment from the server
            	 */
            	if(selectedComment != -1){
	        		RestaurantCommentUpdate restaurantCommentUpdate = new RestaurantCommentUpdate();
	        		restaurantCommentUpdate.removeRestaurantComment(selectedComment);
	            	
	        		//Reset the selectedComment
	        		selectedComment = -1;
	        		
	        		// TODO : Refresh activity
	        		Intent intent = getIntent();
	                finish();
	                startActivity(intent);

	                dialog.cancel();
            	}
            }
        });
        builder1.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            	
            	//Reset the selectedComment
        		selectedComment = -1;
            	
        		dialog.cancel();
            }
        });

        final AlertDialog alert11 = builder1.create();
        
        restaurantCommentListView.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
            	int userId = userIdList.get(position);
            	if(userId == Owner.id){
            		// TODO : Implement pop up ask if delete of message
            		selectedComment = commentIdList.get(position);
            		alert11.show();
            	}
            	return false;
            }
        }); 
        /*
        restaurantCommentListView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
            	if(event.getAction()!= MotionEvent.ACTION_UP){
            		return false;
            	}
            	
            	int itemNum = restaurantCommentListView.getCount();
                
                if(itemNum == 0){
                	return false;
                }
                
                //Transform the y to position
            	float y = (int) event.getY();
                float itemHeight = restaurantCommentListView.getHeight()/itemNum;
                int position = -1;
                
                for(int i=0;i<NUM_MEAL;i++){
                	float lower = i*itemHeight;
                	float upper = lower + itemHeight;
                	if(y>lower && y<upper){
                		position = i;
                	}
                }
                
                if(position>NUM_MEAL-1 || position<0){
                	return false;
                }
                
            	int userId = userIdList.get(position);
                
                //Jump to FoodFoodPageActivity
                Intent intentPass = new Intent(RestaurantPageActivity.this, UserProfileActivity.class);
				
				//Pass pass intent								
				intentPass.putExtra("USERID",Integer.toString(userId).trim());
					
				//Go to next page
				startActivity(intentPass);
                // Disallow the touch request for parent scroll on touch of
                // child view
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        */
        Helper.setListViewHeightBasedOnChildren(restaurantCommentListView);
        
        //Release unused ram
        System.gc();
    }
    
    public void addListenerOnRatingBar() {
    	 
    	ratingBar = (RatingBar) findViewById(R.id.rest_rating_bar);
    	ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
    		public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
    			createDialog(rating);
    		}
    	});
      }
    protected void createDialog(final float rating) {
    	LayoutInflater factory = LayoutInflater.from(this);

    	final int rating_int = (int)Math.ceil(rating);

        final View textEntryView = factory.inflate(R.layout.restaurant_page_comment_dialog, null);
        
        TextView tv_rest_dialog_rating = (TextView) textEntryView.findViewById(R.id.rest_dialog_rating);
        tv_rest_dialog_rating.setText("Your Rating = " + Integer.toString(rating_int) + "/5");
        
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setView(textEntryView)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked OK so do some stuff */
                	/*upload comment*/
                	RestaurantCommentUpdate restaurantCommentUpdate = new RestaurantCommentUpdate();
                	//Get text from edit text
                	EditText et_food_page_comment_dialog_comment = (EditText) textEntryView.findViewById(R.id.restaurant_page_comment_dialog_comment);
                	String comment = et_food_page_comment_dialog_comment.getText().toString();
                	
                	//Do not allow posting empty comment
                	if(comment.isEmpty()){
                		Toast.makeText(getApplicationContext(), "Post Cancel",Toast.LENGTH_SHORT).show();
                		return;
                	}
                	
                	//Convert rating to int
                	
                	//Check if posting of comment is successful
                	int SUCCESS = 1;
                	if(SUCCESS == restaurantCommentUpdate.uploadRestaurantComment(Owner.id, restaurantId,rating_int,comment)){
                		Toast.makeText(getApplicationContext(), "Comment Posted",Toast.LENGTH_SHORT).show();
                	}else{
                		Toast.makeText(getApplicationContext(), "Fail to post comment, please try again",Toast.LENGTH_LONG).show();
                	}
                	
                	//Reload the list view in user review
                	Intent intent = getIntent();
                    finish();
                    startActivity(intent);
                	
                }
            })
            .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked cancel so do some stuff */
                	
                	
                }
            });
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
    
    /*
     * List containing the list of food of that restaurant
     */
    private List<Map<String, Object>> getMealListView() {
    	
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		mealIdList = new ArrayList<Integer>();
		
		MealFetch mealFetch = new MealFetch();
		List<Meal> mealList = mealFetch.fetchAllMealByRestaurantId(restaurantId);
	    
	    //List<Restaurant> restaurantList = restaurantFetch.fetchAllRestaurant();
	    
	    if(mealList != null){
	    	int counter = 0;
		    for(Meal meal : mealList){
		    	if(counter > NUM_MEAL-1){
		    		
		    		break;
		    	}else{
		    		counter++;
		    	}
		    	
				Map<String, Object> map = new HashMap<String, Object>();
				
				if(meal.getPicture()!=null){
					
					mealPictureDrawableURL = Configuration.baseURL + meal.getPicture();
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  
							tmpPicture = loadImageFromURL(mealPictureDrawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
				}
				
				
				map.put("food_pic", tmpPicture);
				map.put("food_name", meal.getName());
				map.put("price", "$" + meal.getPrice());
				
				list.add(map);
				mealIdList.add(meal.getId());
				
	    	}
	    }

		return list;
	}
    
    
    private List<Map<String, Object>> getRestaurantComment() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		
		userIdList = new ArrayList<Integer>();
		commentIdList = new ArrayList<Integer>();
		
		RestaurantCommentFetch restaurantCommentFetch = new RestaurantCommentFetch();
		List<RestaurantComment> restaurantCommentList = restaurantCommentFetch.fetchRestaurantCommentByRestaurantId(restaurantId);
		
		if(restaurantCommentList != null){
	    	int counter = 0;
	    	for(RestaurantComment restaurantComment : restaurantCommentList){
		    	if(counter > NUM_MEAL-1){
		    		break;
		    	}else{
		    		counter++;
		    	}
		    	
				Map<String, Object> map = new HashMap<String, Object>();
				
				UserFetch userFetch = new UserFetch();
				User user = userFetch.fetchUserById(restaurantComment.getUser());
				
				if(user.getProfilePicture()!=null){
					
					userProfilePictureDrawableURL = Configuration.baseURL + user.getProfilePicture();
					
					//Start a new thread and use POST method to send telephone and passcode to authURL
			        //Start a new thread to attempt Login (requirement when connecting online)
					Thread attemptThread = new Thread(new Runnable(){  
						public void run(){  
							tmpPicture = loadImageFromURL(userProfilePictureDrawableURL);		
						}
					});  
					attemptThread.start();
					
					while(attemptThread.isAlive()){
						//Wait for server response
					}
				}
				
				
				map.put("user_review_pic",tmpPicture);
				map.put("user_name", userFetch.fetchUserNameById(restaurantComment.getUser()));
				map.put("comments", restaurantComment.getComment());
				map.put("time", restaurantComment.getCreateDate());
				map.put("user_rating", restaurantComment.getRating() + "/5");
				
				
				list.add(map);
				
				userIdList.add(user.getId());
				commentIdList.add(restaurantComment.getId());
	    	}
	    }
		
		
		
		return list;
	}

    private Drawable loadImageFromURL(String url){
        try{
        	InputStream is = (InputStream) new URL(url).getContent();
            Bitmap tmp = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeStream(is),Configuration.THUMBSIZE,Configuration.THUMBSIZE);
            return new BitmapDrawable(getResources(), tmp);
        	/*
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable draw = Drawable.createFromStream(is, "src");
            return draw;
            */
        }catch (Exception e) {
            //TODO handle error
            Log.i("loadingImg", e.toString());
            return null;
        }
    }
    
    
}